﻿using ShopFine.Models;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;

namespace ShopFine.Admins
{
    public partial class ProductManagement : System.Web.UI.Page
    {
        ProductDAO producDao;
        public ProductManagement()
        {
            producDao = new ProductDAO();
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            Page.Form.Attributes.Add("enctype", "multipart/form-data");
            if (!IsPostBack)
            {
            }
        }

        protected void RadGrid1_NeedDataSource(object sender, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
        {
            RadGrid1.DataSource = new ProductDAO().GetAll();
        }

        protected void RadGrid1_ItemCreated(object sender, Telerik.Web.UI.GridItemEventArgs e)
        {
            if (e.Item is GridFilteringItem)
            {
                GridFilteringItem filteringItem = e.Item as GridFilteringItem;
                (filteringItem["ProductCode"].Controls[0] as TextBox).Width = Unit.Pixel(60);
                (filteringItem["Name"].Controls[0] as TextBox).Width = Unit.Pixel(100);
            }
        }

        protected void RadGrid1_ItemCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
        {
            
        }

        bool checkFileUpload(FileUpload fileupload)
        {
            FileUpload fu = fileupload;
            if (fileupload.HasFile)
            {
                String fileExtension = System.IO.Path.GetExtension(fu.FileName).ToLower();
                String[] allowedExtensions = { ".gif", ".png", ".jpeg", ".jpg" };
                for (int i = 0; i < allowedExtensions.Length; i++)
                {
                    if (fileExtension == allowedExtensions[i])
                    {
                        return true;
                    }
                }
            }
            return false;
        }
        string upload_Image(FileUpload fileupload, string ImageSavedPath, ref Label lblmessage)
        {
            FileUpload fu = fileupload;
            string imagepath = "";
            if (fileupload.HasFile)
            {
                string filepath = Server.MapPath(ImageSavedPath);
                String fileExtension = System.IO.Path.GetExtension(fu.FileName).ToLower();
                String[] allowedExtensions = { ".gif", ".png", ".jpeg", ".jpg" };
                for (int i = 0; i < allowedExtensions.Length; i++)
                {
                    if (fileExtension == allowedExtensions[i])
                    {
                        try
                        {
                            string s_newfilename = DateTime.Now.Year.ToString() +
                                DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() +
                                DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + fileExtension;
                            fu.PostedFile.SaveAs(filepath + s_newfilename);

                            imagepath = ImageSavedPath + s_newfilename;
                        }
                        catch (Exception ex)
                        {
                            if (lblmessage != null)
                            {
                                lblmessage.ForeColor = Color.Red;
                                lblmessage.Text = "An error occurs when save file:" + ex.Message;
                                return string.Empty;
                            }
                        }

                    }

                }

            }
            return imagepath;
        }

        protected void RadGrid1_InsertCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
        {
            UserControl userControl = (UserControl)e.Item.FindControl(GridEditFormItem.EditFormUserControlID);
            Label ltrMessage = userControl.FindControl("ltrMessage") as Label;

            Product insertObj = new Product() { ID = -1, IsActive = true };
            insertObj.ProductCode = (userControl.FindControl("inputProductCode") as TextBox).Text.Trim();
            insertObj.Name = (userControl.FindControl("inputTitle") as TextBox).Text.Trim();
            try
            {
                insertObj.Price = Convert.ToInt32((userControl.FindControl("inputPrice") as TextBox).Text.Trim());
            }
            catch (Exception)
            {
                if (ltrMessage != null)
                {
                    ltrMessage.ForeColor = Color.Red;
                    ltrMessage.Text = "Price must be a number.";
                }
                e.Canceled = true;
                return;
            }
            insertObj.Description = (userControl.FindControl("inputDescription") as TextBox).Text.Trim();
            if (insertObj.Price <= 0)
            {
                if (ltrMessage != null)
                {
                    ltrMessage.ForeColor = Color.Red;
                    ltrMessage.Text = "Price must be greater than 0.";
                }
                e.Canceled = true;
                return;
            }
            DropDownList ddlSupplier = userControl.FindControl("ddlSupplier") as DropDownList;
            if (ddlSupplier != null && ddlSupplier.Items.Count > 0)
            {
                insertObj.SupplierID = Convert.ToInt32(ddlSupplier.SelectedValue);
            }

            DropDownList ddlSubCategory = userControl.FindControl("ddlSubCategory") as DropDownList;
            if (ddlSubCategory != null && ddlSubCategory.Items.Count > 0)
            {
                insertObj.SubCategoryID = Convert.ToInt32(ddlSubCategory.SelectedValue);
            }
            else
            {
                if (ltrMessage != null)
                {
                    ltrMessage.ForeColor = Color.Red;
                    ltrMessage.Text = "Please insert sub category to insert product.";
                }
                e.Canceled = true;
                return;
            }

            FileUpload fileKey = userControl.FindControl("FileUploadKey") as FileUpload;
            FileUpload file1 = userControl.FindControl("FileUpload1") as FileUpload;
            FileUpload file2 = userControl.FindControl("FileUpload2") as FileUpload;
            FileUpload file3 = userControl.FindControl("FileUpload3") as FileUpload;
            FileUpload file4 = userControl.FindControl("FileUpload4") as FileUpload;

            if (checkFileUpload(fileKey))
            {
                string uploadimagePath = upload_Image(fileKey, "~/ProductImages/", ref ltrMessage);
                if (string.IsNullOrEmpty(uploadimagePath))
                {
                    return;
                }
                else
                    insertObj.ImageUrl = uploadimagePath;
            }

            var imageUrls = new List<ImageURL>();
            string path = "~/ProductImages/";

            if (checkFileUpload(file1))
            {
                string uploadimagePath = upload_Image(file1, path, ref ltrMessage);
                if (string.IsNullOrEmpty(uploadimagePath))
                {
                    return;
                }
                else
                {
                    imageUrls.Add(new ImageURL() { Url = uploadimagePath, CreateDate = DateTime.Now });
                }
            }

            if (checkFileUpload(file2))
            {
                string uploadimagePath = upload_Image(file2, path, ref ltrMessage);
                if (string.IsNullOrEmpty(uploadimagePath))
                {
                    return;
                }
                else
                {
                    imageUrls.Add(new ImageURL() { Url = uploadimagePath, CreateDate = DateTime.Now });
                }
            }
            if (checkFileUpload(file3))
            {
                string uploadimagePath = upload_Image(file3, path, ref ltrMessage);
                if (string.IsNullOrEmpty(uploadimagePath))
                {
                    return;
                }
                else
                {
                    imageUrls.Add(new ImageURL() { Url = uploadimagePath, CreateDate = DateTime.Now });
                }
            }
            if (checkFileUpload(file4))
            {
                string uploadimagePath = upload_Image(file4, path, ref ltrMessage);
                if (string.IsNullOrEmpty(uploadimagePath))
                {
                    return;
                }
                else
                {
                    imageUrls.Add(new ImageURL() { Url = uploadimagePath, CreateDate = DateTime.Now });
                }
            }

            insertObj.ImageURLs = imageUrls;
            insertObj.CreateDate = DateTime.Now;

            try
            {
                if (producDao.CheckProductCodeExisted(insertObj))
                {
                    if (ltrMessage != null)
                    {
                        ltrMessage.ForeColor = Color.Red;
                        ltrMessage.Text = "Product code is existed in database.";
                    }
                    e.Canceled = true;
                    return;
                }

                if (producDao.Insert(insertObj))
                {
                    error.Visible = false;
                    success.Visible = true;
                    ltrSuccess.Text = "Add new product successfully";
                    RadGrid1.MasterTableView.IsItemInserted = true;
                    RadGrid1.MasterTableView.Rebind();
                }
            }
            catch (Exception ex)
            {
                if (ltrMessage != null)
                {
                    ltrMessage.ForeColor = Color.Red;
                    ltrMessage.Text = ex.Message;
                }
                e.Canceled = true;
                return;
            }
        }

        protected void RadGrid1_UpdateCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
        {
            UserControl userControl = (UserControl)e.Item.FindControl(GridEditFormItem.EditFormUserControlID);
            GridEditableItem editedItem = e.Item as GridEditableItem;
            string productID = editedItem.OwnerTableView.DataKeyValues[editedItem.ItemIndex]["ID"].ToString();
            Product updateObj = producDao.GetProductByID(Convert.ToInt32(productID));
            Label ltrMessage = userControl.FindControl("ltrMessage") as Label;
            if(updateObj == null)
            {
                if (ltrMessage != null)
                {
                    ltrMessage.ForeColor = Color.Red;
                    ltrMessage.Text = "Product not found.";
                }
                e.Canceled = true;
                return;
            }
            updateObj.Name = (userControl.FindControl("inputTitle") as TextBox).Text.Trim();
            try
            {
                updateObj.Price = Convert.ToInt32((userControl.FindControl("inputPrice") as TextBox).Text.Trim());
            }
            catch (Exception)
            {
                if (ltrMessage != null)
                {
                    ltrMessage.ForeColor = Color.Red;
                    ltrMessage.Text = "Price must be a number.";
                }
                e.Canceled = true;
                return;
            }
            updateObj.Description = (userControl.FindControl("inputDescription") as TextBox).Text.Trim();
            if (updateObj.Price <= 0)
            {
                if (ltrMessage != null)
                {
                    ltrMessage.ForeColor = Color.Red;
                    ltrMessage.Text = "Price must be greater than 0.";
                }
                e.Canceled = true;
                return;
            }
            DropDownList ddlSupplier = userControl.FindControl("ddlSupplier") as DropDownList;
            if (ddlSupplier != null && ddlSupplier.Items.Count > 0)
            {
                updateObj.SupplierID = Convert.ToInt32(ddlSupplier.SelectedValue);
            }

            DropDownList ddlSubCategory = userControl.FindControl("ddlSubCategory") as DropDownList;
            if (ddlSubCategory != null && ddlSubCategory.Items.Count > 0)
            {
                updateObj.SubCategoryID = Convert.ToInt32(ddlSubCategory.SelectedValue);
            }
            else
            {
                if (ltrMessage != null)
                {
                    ltrMessage.ForeColor = Color.Red;
                    ltrMessage.Text = "Please insert sub category to insert product.";
                }
                e.Canceled = true;
                return;
            }
            string path = "~/ProductImages/";

            FileUpload fileKey = userControl.FindControl("FileUploadKey") as FileUpload;
            FileUpload file1 = userControl.FindControl("FileUpload1") as FileUpload;
            FileUpload file2 = userControl.FindControl("FileUpload2") as FileUpload;
            FileUpload file3 = userControl.FindControl("FileUpload3") as FileUpload;
            FileUpload file4 = userControl.FindControl("FileUpload4") as FileUpload;
            if (checkFileUpload(fileKey))
            {

                string uploadimagePath = upload_Image(fileKey, path, ref ltrMessage);
                if (string.IsNullOrEmpty(uploadimagePath))
                {
                    return;
                }
                else
                    updateObj.ImageUrl = uploadimagePath;
            }

            if (checkFileUpload(file1))
            {
                string uploadimagePath = upload_Image(file1, path, ref ltrMessage);
                if(updateObj.ImageURLs.Count > 0)
                {
                    if (string.IsNullOrEmpty(uploadimagePath))
                    {
                        return;
                    }
                    else
                    {
                        updateObj.ImageURLs.OrderBy(p=>p.ID).FirstOrDefault().Url = uploadimagePath;
                        updateObj.ImageURLs.OrderBy(p=>p.ID).FirstOrDefault().CreateDate = DateTime.Now;
                    }
                }
                else
                    updateObj.ImageURLs.Add(new ImageURL(){Url=uploadimagePath, CreateDate = DateTime.Now});
            }

            if (checkFileUpload(file2))
            {
                string uploadimagePath = upload_Image(file2, path, ref ltrMessage);
                if(updateObj.ImageURLs.Count > 1)
                {
                    if (string.IsNullOrEmpty(uploadimagePath))
                    {
                        return;
                    }
                    else
                    {
                        if(File.Exists(updateObj.ImageURLs.OrderBy(p=>p.ID).Take(2).LastOrDefault().Url))
                        {
                            File.Delete(updateObj.ImageURLs.OrderBy(p=>p.ID).Take(2).LastOrDefault().Url);
                        }
                        updateObj.ImageURLs.OrderBy(p=>p.ID).Take(2).LastOrDefault().Url = uploadimagePath;
                        updateObj.ImageURLs.OrderBy(p=>p.ID).Take(2).LastOrDefault().CreateDate = DateTime.Now;
                    }
                }
                else
                {
                    updateObj.ImageURLs.Add(new ImageURL(){Url=uploadimagePath, CreateDate = DateTime.Now});
                }
            }

            if (checkFileUpload(file3))
            {
                string uploadimagePath = upload_Image(file3, path, ref ltrMessage);
                if(updateObj.ImageURLs.Count > 2)
                {
                    if (string.IsNullOrEmpty(uploadimagePath))
                    {
                        return;
                    }
                    else
                    {
                        // delete old file
                        if(File.Exists(updateObj.ImageURLs.OrderBy(p=>p.ID).Take(3).LastOrDefault().Url))
                        {
                            File.Delete(updateObj.ImageURLs.OrderBy(p=>p.ID).Take(3).LastOrDefault().Url);
                        }
                        updateObj.ImageURLs.OrderBy(p=>p.ID).Take(3).LastOrDefault().Url = uploadimagePath;
                        updateObj.ImageURLs.OrderBy(p=>p.ID).Take(3).LastOrDefault().CreateDate = DateTime.Now;
                    }
                }
                else
                {
                    updateObj.ImageURLs.Add(new ImageURL(){Url=uploadimagePath, CreateDate = DateTime.Now});
                }
            }

            if (checkFileUpload(file4))
            {
                string uploadimagePath = upload_Image(file4, path, ref ltrMessage);
                if(updateObj.ImageURLs.Count > 3)
                {
                    if (string.IsNullOrEmpty(uploadimagePath))
                    {
                        return;
                    }
                    else
                    {
                        if(File.Exists(updateObj.ImageURLs.OrderBy(p=>p.ID).Take(4).LastOrDefault().Url))
                        {
                            File.Delete(updateObj.ImageURLs.OrderBy(p=>p.ID).Take(4).LastOrDefault().Url);
                        }
                        updateObj.ImageURLs.OrderBy(p=>p.ID).Take(4).LastOrDefault().Url = uploadimagePath;
                        updateObj.ImageURLs.OrderBy(p=>p.ID).Take(4).LastOrDefault().CreateDate = DateTime.Now;
                    }
                }
                else
                {
                    updateObj.ImageURLs.Add(new ImageURL() { Url = uploadimagePath, CreateDate = DateTime.Now });
                }
            }

            try 
	        {	        
		        if (producDao.CheckProductCodeExisted(updateObj))
                {
                    if (ltrMessage != null)
                    {
                        ltrMessage.ForeColor = Color.Red;
                        ltrMessage.Text = "Product code is existed in database.";
                    }
                    e.Canceled = true;
                    return;
                }

                if (producDao.Update(updateObj))
                {
                    error.Visible = false;
                    success.Visible = true;
                    ltrSuccess.Text = "Update product successfully";
                    RadGrid1.MasterTableView.Rebind();
                }
	        }
	        catch (Exception ex)
	        {
		        if (ltrMessage != null)
                {
                    ltrMessage.ForeColor = Color.Red;
                    ltrMessage.Text = ex.Message;
                }
                e.Canceled = true;
                return;
	        }
        }

        protected void RadGrid1_DeleteCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
        {

        }

        protected void RadGrid1_EditCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
        {

        }

        protected void RadGrid1_ItemDataBound(object sender, Telerik.Web.UI.GridItemEventArgs e)
        {

        }
    }
}